const request = require('../index');
const baseUrl = require('../baseUrl');

async function setHeaders() {
  const { data } = await getBuvid();
  const b_3 = data.data.b_3 ? data.data.b_3 : '0';
  return {
    Referer: baseUrl.bili,
    cookie: `buvid3=${b_3}`,
  };
}

// 获取
const getBuvid = () => {
  return request({
    method: 'GET',
    url: `${baseUrl.biliAPI}/x/frontend/finger/spi`,
  });
};
exports.searchBili = async (keyword, currentPage) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    url: `${baseUrl.biliAPI}/x/web-interface/wbi/search/type`,
    headers,
    params: {
      search_type: 'video',
      order: 'totalrank',
      page: currentPage,
      page_size: 20,
      keyword,
    },
  });
};

exports.getAudioCid = async (bvid) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    url: `${baseUrl.biliAPI}/x/web-interface/view`,
    headers,
    params: { bvid },
  });
};

exports.getAudioStreamingUrl = async (bvid, cid) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    headers,
    url: `${baseUrl.biliAPI}/x/player/wbi/playurl?fnval=16&bvid=${bvid}&cid=${cid}`,
  });
};

// 获取音频流
exports.getBiliAudioStreaming = async (songStreamingUrl) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    responseType: 'arraybuffer',
    headers,
    url: songStreamingUrl,
  });
};

exports.searchMenu = async (currentPage) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    headers,
    url: `${baseUrl.bili}/audio/music-service-c/web/menu/hit`,
    params: {
      pn: currentPage,
      ps: 20,
    },
  });
};

exports.getMenuInfo = async (sid) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    headers,
    url: `${baseUrl.bili}/audio/music-service-c/web/menu/info`,
    params: {
      sid,
    },
  });
};

exports.getMenuList = async (params) => {
  const headers = await setHeaders();
  return request({
    method: 'GET',
    headers,
    url: `${baseUrl.bili}/audio/music-service-c/web/song/of-menu`,
    params,
  });
};
